<template>
  <div class="p24 page-miH page-bgBack">
    <a-layout>
      <a-row type="flex" justify="space-between" style="margin-bottom: 24px">
        <a-col :span="4">
          <a-input-search v-model="searchName" placeholder="搜索方案" allow-clear @search="handleSearch" />
        </a-col>
        <a-col>
          <a-button v-if="isContainByString('contractAdmin')" type="primary" @click="showIssueModa" style="margin-right: 10px">
            下发参保方案
          </a-button>
          <a-button type="primary" @click="enterAddMethod"> <a-icon type="plus" />添加参保方案 </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-table
          :data-source="methodList"
          :pagination="pagination"
          :columns="columns"
          row-key="id"
          :scroll="{ x: 800 }"
          @change="handlePageChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span>{{ props.value }}条/页</span>
          </template>
          <template slot="progName" slot-scope="text">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ text }}</span>
              </template>
              <span>{{ getProgName(text) }}</span>
            </a-tooltip>
          </template>
          <span slot="onlySocAmount" slot-scope="text">{{ text ? "仅设置参保金额" : "设置参保金额和比例" }}</span>
          <template slot="action" slot-scope="text, record">
            <span class="opreate" @click="enterDetail(record.id)">查看</span>
          </template>
        </a-table>
      </a-row>
    </a-layout>
    <!-- 删除方案弹框 -->
    <a-modal :visible="isDelete" title="删除参保方案" @ok="handleChange">
      <div class="delete-box">
        确定要删除
        <span>青岛方案</span>？
      </div>
    </a-modal>
    <a-modal
      :visible="issueModalVisible"
      title="下发参保方案"
      width="538px"
      :destroy-on-close="true"
      @ok="confirmIssueModal"
      @cancel="handleCancelIssueModal"
    >
      <a-row>
        <a-col :span="12">
          <span>请选择参保方案</span>
          <a-select
            v-model="contractList"
            mode="multiple"
            show-search
            placeholder="请选择参保方案"
            option-filter-prop="children"
            style="width: 240px; margin-top: 10px"
          >
            <a-select-option v-for="(item, index) in contractData" :key="index" :value="item.id">
              <a-tooltip placement="left" :title="item.progName">
                {{ item.progName }}
              </a-tooltip>
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="12">
          <span>请选择下发用工单位</span>
          <a-tree-select
            :value="companyList"
            :treeData="dataList"
            :filterTreeNode="filterTreeNode"
            treeCheckable
            placeholder="请选择用工单位"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
            @change="companySelectChange"
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { pageRelation, deleteSocProgs, socProgListAll } from "@/api/shebao/shebaoMethod";
import { isContainByString } from "@/utils/index";
import { findCompanyGroup } from "@/api/company/contract";
import { saveIssuedSocProg } from "./api";
import { formatCompanyTree } from "@/utils/tools";
const columns = [
  {
    title: "方案名称",
    dataIndex: "progName",
    align: "center",
    fixed: "left",
    scopedSlots: { customRender: "progName" },
    width: 180
  },

  {
    title: "参保城市",
    dataIndex: "socCityName",
    align: "center",
    width: 150,
    ellipsis: true
  },
  {
    title: "方案类型",
    dataIndex: "onlySocAmount",
    align: "center",
    ellipsis: true,
    width: 180,
    scopedSlots: { customRender: "onlySocAmount" }
  },
  {
    title: "使用人数",
    dataIndex: "empCount",
    align: "center",
    ellipsis: true,
    width: 100
  },
  {
    title: "社保基数",
    dataIndex: "socCardinality",
    align: "center",
    ellipsis: true,
    width: 360
  },
  {
    title: "公积金基数",
    dataIndex: "pfCardinality",
    align: "center",
    ellipsis: true,
    width: 200
  },
  {
    title: "操作",
    key: "action",
    align: "center",
    fixed: "right",
    width: 80,
    scopedSlots: { customRender: "action" }
  }
];
export default {
  data() {
    return {
      isContainByString,
      columns,
      companyId: this.$store.state.hr.companyId,
      isDelete: false,
      methodList: [],
      searchName: undefined,
      id: "",
      progName: "",
      dataList: [],
      socCityName: "",
      socCity: "",
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共${total}条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"],
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        }
      },
      // modal显示隐藏
      issueModalVisible: false,
      // 下发选择框合同数据
      contractData: [],
      // 已选的合同模板数据
      contractList: [],
      // 已选的公司数据
      companyList: []
    };
  },
  created() {
    this.findCompanyGroup();
    this.getPageRelation();
    this.socProgListAll();
  },
  methods: {
    filterTreeNode(inVal, node) {
      if (node.data.props.title.toLowerCase().indexOf(inVal.toLowerCase()) >= 0) {
        return true;
      }
      return false;
    },
    companySelectChange(companyKeys) {
      this.companyList = companyKeys.filter((item) => item.includes("_company_"));
    },
    getProgName(txt) {
      if (txt.length > 10) {
        return txt.substring(0, 10);
      } else {
        return txt;
      }
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = formatCompanyTree(res.data);
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    handleSearch() {
      this.pagination.current = 1;
      this.getPageRelation();
    },
    // 分页查询
    handlePageChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.getPageRelation();
    },

    enterAddMethod() {
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "shebao"}/shebaoMethod/addMethod`
      });
    },
    // 保存删除参保方案
    handleChange() {
      this.isDelete = false;
    },
    // 点击删除参保方案
    deleteMethod(id, empCount) {
      var that = this;
      this.$confirm({
        title: "删除方案",
        content: "确认删除方案？",
        onOk() {
          if (empCount !== 0) {
            that.$notification["error"]({
              message: "删除失败",
              description: "该参保方案还有参保人使用，不能删除！"
            });
            return;
          } else {
            const data = {
              id: id
            };
            deleteSocProgs(data)
              .then((res) => {
                if (res.code === 200) {
                  that.$notification["success"]({
                    message: "删除成功"
                  });
                }
                that.getPageRelation();
              })
              .catch((err) => {
                console.log("debug log --> ", err);
              });
          }
        }
      });
    },
    enterDetail(id) {
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "shebao"}/shebaoMethod/methodDetail`,
        query: {
          id
        }
      });
    },
    // 查询获取当前社保方案列表
    getPageRelation() {
      const data = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        progName: this.searchName,
        companyId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      };
      pageRelation(data).then((res) => {
        if (res.data.entityCount) this.pagination.total = res.data.entityCount;
        if (res.data.entities) this.methodList = res.data.entities;

        if (!res.data.entities) {
          this.pagination.total = 0;
          this.methodList = [];
        }
      });
    },
    socProgListAll() {
      const data = {
        companyId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      };
      socProgListAll(data)
        .then((res) => {
          this.contractData = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 下发参保方案
    saveIssuedSocProg() {
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的合同模板"
        });
        return;
      }
      const companyArr = Array.from(new Set(this.companyList.map((item) => item.split("_")[2])));
      const data = {
        companyIds: companyArr,
        socProgIds: this.contractList
      };
      saveIssuedSocProg(data)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          // this.$notification["error"]({
          //   message: "错误",
          //   description: "下发失败"
          // });
        });
    },

    // 方法
    confirmIssueModal() {
      // TODO 下发接口
      this.saveIssuedSocProg();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
      // 已选的合同模板数据
      this.contractList = [];
      // 已选的公司数据
      this.companyList = [];
    },
    showIssueModa() {
      this.issueModalVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.opreate {
  color: var(--primary);
  cursor: pointer;
}
</style>
